package com.cheyunkeji.er.fragment.evaluate;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.DeleteObjectRequest;
import com.alibaba.sdk.android.oss.model.DeleteObjectResult;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.AppearanceCheckBCSM;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.ConvertUtils;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.evaluate.AppearanceCheckDialog;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Michael on 2017/6/8 14:47.
 */

public class AppearanceCheckFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener, View.OnTouchListener, View.OnLongClickListener, EvaluateWorkflowActivity.OnOutActionListener, AppearanceCheckDialog.OnDialogCheckedListener, OssService.onImageProcessedResultListener {


    public static final int PAGE_INDEX = 5;
    private static final String TAG = AppearanceCheckFragment.class.getSimpleName();
    private static final int PREVIEW_IMG_REQUEST = 0x110;
    @BindView(R.id.tv_previous_step)
    TextView tvPreviousStep;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @BindView(R.id.ll_bottom_view)
    LinearLayout llBottomView;
    @BindView(R.id.rb_hua)
    RadioButton rbHua;
    @BindView(R.id.rb_bian)
    RadioButton rbBian;
    @BindView(R.id.rb_xiu)
    RadioButton rbXiu;
    @BindView(R.id.rb_lie)
    RadioButton rbLie;
    @BindView(R.id.rb_ao)
    RadioButton rbAo;
    @BindView(R.id.rb_fix)
    RadioButton rbFix;
    @BindView(R.id.rg_problem_desc)
    RadioGroup rgProblemDesc;
    @BindView(R.id.rb_size_100)
    RadioButton rbSize100;
    @BindView(R.id.rb_size_200)
    RadioButton rbSize200;
    @BindView(R.id.rb_size_300)
    RadioButton rbSize300;
    @BindView(R.id.rg_size)
    RadioGroup rgSize;
    @BindView(R.id.iv_display)
    ImageView ivDisplay;
    @BindView(R.id.rl_container)
    RelativeLayout rlContainer;
    @BindView(R.id.rl_bcsm)
    RelativeLayout rlBcsm;
    //    图片上传次数计数器
    private int uploadImgCounter = 0;
    private Bitmap bitmap;
    private ArrayList<TextView> tvList;
    private ArrayList<Integer> rbTextDescList = null;
    private ArrayList<Integer> rbSizeList = null;

    private ImageCaptureManager captureManager;

    //    车辆外观故障区域描述
    private String[] textDescs = Constants.errStateDESCS;

    //      字体大小
    private int[] textSizes = new int[]{11, 13, 20};
    //     原型图标大小
    private int[] circleSizes = new int[]{25, 30, 35};

    //      当前选中圆形图标大小
    private int currentCircleSize = 25;
    //      当前选中车辆故障描述
    private String currentText = "划";

    //    当前选中字体大小 ： 11 、 13 、20 sp
    private int currentTextSize = 11;

    private AppearanceCheckDialog dialog;

    //    需要被删除照片的OSS地址
    private ArrayList<String> needToDeleteOSSImgList;


    private List<EvaluateDetailResult2.DetectionBean.ApshellBean> shellList;
    private Runnable mTask;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {

        contentView = inflater.inflate(R.layout.er_frag_appearance_check, container, false);
        ButterKnife.bind(this, contentView);

    }

    @Override
    protected void init() {

        captureManager = new ImageCaptureManager(getActivity());

        ivDisplay.setOnTouchListener(this);
        tvList = new ArrayList<>();
        needToDeleteOSSImgList = new ArrayList<>();

//      获取ImageView背景图Bitmap
        bitmap = ((BitmapDrawable) ivDisplay.getBackground()).getBitmap();

        rbTextDescList = new ArrayList<>(6);
        rbTextDescList.add(R.id.rb_hua);
        rbTextDescList.add(R.id.rb_bian);
        rbTextDescList.add(R.id.rb_xiu);
        rbTextDescList.add(R.id.rb_lie);
        rbTextDescList.add(R.id.rb_ao);
        rbTextDescList.add(R.id.rb_fix);

        rbSizeList = new ArrayList<>(3);
        rbSizeList.add(R.id.rb_size_100);
        rbSizeList.add(R.id.rb_size_200);
        rbSizeList.add(R.id.rb_size_300);

    }

    @Override
    protected void initView() {

        tvPreviousStep.setOnClickListener(this);
        tvNextStep.setOnClickListener(this);
        rgProblemDesc.setOnCheckedChangeListener(this);
        rgSize.setOnCheckedChangeListener(this);
        rlBcsm.setOnClickListener(this);

        dialog = new AppearanceCheckDialog(this.getActivity(), this);

    }

    @Override
    protected void initData() {

        if (null != MyApplication.getInstance().getEvaluateResult() && null != MyApplication.getInstance().getEvaluateResult().getDetection() && null != MyApplication.getInstance().getEvaluateResult().getDetection().getApshell()) {

            shellList = MyApplication.getInstance().getEvaluateResult().getDetection().getApshell();

//            rlContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//                @Override
//                public void onGlobalLayout() {
//                    displayInfo();
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
//                    rlContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                    else
//                        rlContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                }
//            });
            rlContainer.post(new Runnable() {
                @Override
                public void run() {
                    displayInfo();
                }
            });
        }
    }

    /**
     * 重绘所有圆点
     */
    private void displayInfo() {

        for (EvaluateDetailResult2.DetectionBean.ApshellBean apshellBean : shellList) {

            addTextViewToSpecifiedPoint(getActivity(), textDescs[apshellBean.getStatus() - 1],
                    textSizes[apshellBean.getSize() / 100 - 1], circleSizes[apshellBean.getSize() / 100 - 1],
                    apshellBean.getX() * ivDisplay.getWidth(), apshellBean.getY() * ivDisplay.getHeight(), apshellBean.getImage()).setTag(apshellBean);

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.tv_previous_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToPreviousPage();
                    }
                });

                break;
            case R.id.tv_next_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToNextPage();
                    }
                });
                break;
            case R.id.rl_bcsm:
                startActivity(new Intent(getActivity(), AppearanceCheckBCSM.class));
                break;

            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        if (group == rgProblemDesc) {

            switch (checkedId) {
                case R.id.rb_hua:
                    currentText = textDescs[0];
                    break;
                case R.id.rb_bian:
                    currentText = textDescs[1];
                    break;
                case R.id.rb_xiu:
                    currentText = textDescs[2];
                    break;
                case R.id.rb_lie:
                    currentText = textDescs[3];
                    break;
                case R.id.rb_ao:
                    currentText = textDescs[4];
                    break;
                case R.id.rb_fix:
                    currentText = textDescs[5];
                    break;

                default:
                    break;
            }

        } else if (group == rgSize) {

            switch (checkedId) {
                case R.id.rb_size_100:
                    currentCircleSize = circleSizes[0];
                    currentTextSize = textSizes[0];
                    break;
                case R.id.rb_size_200:
                    currentCircleSize = circleSizes[1];
                    currentTextSize = textSizes[1];
                    break;
                case R.id.rb_size_300:
                    currentCircleSize = circleSizes[2];
                    currentTextSize = textSizes[2];
                    break;

                default:
                    break;
            }
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                Log.e(TAG, "onTouch: x : " + event.getX());
                Log.e(TAG, "onTouch: y : " + event.getY());
                Log.e(TAG, "onTouch: Raw X : " + event.getRawX());
                Log.e(TAG, "onTouch: Raw Y ：" + event.getRawY());

                float width = ivDisplay.getWidth() * 1.0f / bitmap.getWidth();
                float height = ivDisplay.getHeight() * 1.0f / bitmap.getHeight();

                int pixel = bitmap.getPixel((int) (event.getX() / width), (int) (event.getY() / height));

                if (pixel != Color.TRANSPARENT) {

                    Log.e(TAG, "onTouch: 像素值 " + pixel);

                    TextView addedTv = addTextViewToSpecifiedPoint(this.getActivity(), currentText, currentTextSize, currentCircleSize, event.getX(), event.getY(), null);

                    //      创建ApshellBean 作为TextView的 Tag
                    addedTv.setTag(new EvaluateDetailResult2.DetectionBean.ApshellBean(event.getX() / ivDisplay.getWidth(),
                            event.getY() / ivDisplay.getHeight(), 100 * ((rbSizeList.indexOf(rgSize.getCheckedRadioButtonId()) + 1)), "",
                            1 + rbTextDescList.indexOf(rgProblemDesc.getCheckedRadioButtonId())));
                }

                Log.e(TAG, "onTouch:  " + tvList.size());

                break;

            default:
                break;
        }

        return false;
    }

    /**
     * 添加TextView至指定坐标点
     *
     * @param context
     * @param textDesc
     * @param textSize
     * @param circleSize
     * @param x
     * @param y
     * @return
     */
    public TextView addTextViewToSpecifiedPoint(Context context, String textDesc, int textSize, int circleSize, float x, float y, String imgPath) {

        TextView tv = new TextView(context);
        tv.setText(textDesc);
        tv.setTextColor(Color.WHITE);

        if (TextUtils.isEmpty(imgPath))
            tv.setBackgroundResource(R.drawable.small_red_circle);
        else
            tv.setBackgroundResource(R.drawable.small_golden_circle);

        tv.setTextSize(textSize);
        tv.setGravity(Gravity.CENTER);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ConvertUtils.dp2px(circleSize), ConvertUtils.dp2px(circleSize));


        layoutParams.leftMargin = (int) x - ConvertUtils.dp2px(circleSize / 2);
        layoutParams.topMargin = (int) y - ConvertUtils.dp2px(circleSize / 2);

        tv.setLayoutParams(layoutParams);
        rlContainer.addView(tv);

        tv.setOnLongClickListener(this);
        tvList.add(tv);

        return tv;

    }

    @Override
    public boolean onLongClick(View v) {

        Log.e(TAG, "===========onLongClick==============: " + v.getTag().toString());

//        如果有图片，则显示预览按钮，否则隐藏
        if (TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.ApshellBean) v.getTag()).getImage()))
            dialog.showDialogWithoutPreview();
        else
            dialog.showDialogWithPreView();

        dialog.setCurrentLongClickedView(v);

        return false;

    }

    @Override
    public void onSaveEvaluateResult(Runnable task) {

        if (null != task)
            this.mTask = task;

//       删除被替换的OSS图片
        if (needToDeleteOSSImgList != null && needToDeleteOSSImgList.size() > 0) {
            for (String ossImgPath : needToDeleteOSSImgList) {
                deleteImg(ossImgPath);
            }
            needToDeleteOSSImgList.clear();
        }

//       上传图片
        for (TextView tv : tvList) {
            if (!TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.ApshellBean) tv.getTag()).getImage()) && !((EvaluateDetailResult2.DetectionBean.ApshellBean) tv.getTag()).getImage().startsWith("http")) {
                uploadImgToOss();
                return;   //只要至少选择过一张图片，就直接return调用uploadImgToOss方法进行上传图片，否则没有选择照片，直接调用下面的saveData方法上传其他数据
            }
        }

        saveData();

    }


    private void uploadImgToOss() {

        for (TextView tv : tvList) {
            if (!TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.ApshellBean) tv.getTag()).getImage()) && !((EvaluateDetailResult2.DetectionBean.ApshellBean) tv.getTag()).getImage().startsWith("http")) {

                MyApplication.getInstance().getOssService(AppearanceCheckFragment.this).asyncPutImage(OssService.getOssObjectInfo(true),
                        ((EvaluateDetailResult2.DetectionBean.ApshellBean) tv.getTag()).getImage(), tv);
                ++uploadImgCounter;
                showDialog();
            }
        }

    }


    private void saveData() {

        String myData = new StringBuilder("{\"apshell\":").append(new Gson().toJson(getResult())).append("}").toString();

        Log.e(TAG, "saveData: 点区域坐标 ：  " + myData);

        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("aid", MyApplication.getInstance().getEvaluateResult().getAid());
        params.put("detection", myData);

        if (MyApplication.getInstance().getEvaluateResult() == null || MyApplication.getInstance().getEvaluateResult().getIroute() == null || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
            int[] iroute = new int[15];
            iroute[PAGE_INDEX] = 1;
            String json = new Gson().toJson(iroute);
            Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
            params.put("iroute", json.substring(1, json.length() - 1));
        } else {
            MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
            String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
            params.put("iroute", json.substring(1, json.length() - 1));
            Log.e(TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
        }

        //        根据评估类型进行保存或编辑
        int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

//       保存新创建、未上传待评估数据
        if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new RespCallback<EvaluateDetailResult2>() {

                @Override
                protected void onRequestFailed(String msg) {
                    SToast.show(msg);
                    if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                        mTask.run();
                        mTask = null;
                    }
                }

                @Override
                protected void onSuccess(EvaluateDetailResult2 data) {

                    if (null != data) {

                        MyApplication.getInstance().setEvaluateResult(data);
                        if (null != mTask) {
                            mTask.run();
                            mTask = null;
                        }
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }

            });

        } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                    // 网络异常
                    if (e instanceof UnknownHostException || e instanceof SocketException) {
                        SToast.show(R.string.tip_network_error, Gravity.CENTER);
                        return;
                    }
                }

                @Override
                public void onResponse(String response, int id) {

                    try {
                        JSONObject obj = new JSONObject(response);
                        if (obj.optInt("code") == 1) {

                            Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));

                            if (null != mTask) {
                                mTask.run();
                                mTask = null;
                            }

                        } else {
                            SToast.show( obj.optString("msg") );
                            if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                                mTask.run();
                                mTask = null;
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });
        }

    }

    private void goToNextPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarLacquerCheckFragment.PAGE_INDEX);
    }

    private void goToPreviousPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarFrameworkCheckFragment.PAGE_INDEX);
    }


    private List<EvaluateDetailResult2.DetectionBean.ApshellBean> getResult() {

        if (null == shellList)
            shellList = new ArrayList<>();
        else
            shellList.clear();

        for (TextView tv : tvList) {

            shellList.add((EvaluateDetailResult2.DetectionBean.ApshellBean) tv.getTag());

        }

        Log.e(TAG, "onSaveEvaluateResult: " + new Gson().toJson(shellList));

        return shellList;

    }


    @Override
    public void onPreviewImage() {

        Intent intent = new Intent(getActivity(), PhotoPreViewActivity.class);
        intent.putExtra("IMG_PATH", ((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage());
        this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);

    }


    @Override
    public void onTakePhoto() {

        Intent intent = null;
        try {
            intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {

            case ImageCaptureManager.REQUEST_TAKE_PHOTO:

                if (resultCode == RESULT_OK) {
                    captureManager.galleryAddPic();
                    String path = captureManager.getCurrentPhotoPath();
//                    拍摄照片之后改变图标背景
                    dialog.getCurrentLongClickedView().setBackgroundResource(R.drawable.small_golden_circle);
//                  如果拍摄本地照片之后，替换的是服务器照片，则需将服务器照片删除
                    if (!TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage())
                            && ((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage().startsWith("http")) {
                        needToDeleteOSSImgList.add(((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage());
                    }
//                  将图片路径设置为拍摄照片路径
                    ((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).setImage(path);
                }

                break;

            case PhotoPicker.REQUEST_CODE:
                if (data != null) {
                    String localImgPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    if (!TextUtils.isEmpty(localImgPath)) {

                        dialog.getCurrentLongClickedView().setBackgroundResource(R.drawable.small_golden_circle);
//                  如果拍摄本地照片之后，替换的是服务器照片，则需将服务器照片删除
                        if (!TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage())
                                && ((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage().startsWith("http")) {
                            needToDeleteOSSImgList.add(((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).getImage());
                        }
//                  将图片路径设置为拍摄照片路径
                        ((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).setImage(localImgPath);
                    }
                }
                break;


            case PREVIEW_IMG_REQUEST:

                if (data == null) {
                    return;
                }
                boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);
                if (deleteImg) {
                    ((EvaluateDetailResult2.DetectionBean.ApshellBean) dialog.getCurrentLongClickedView().getTag()).setImage("");
                    dialog.getCurrentLongClickedView().setBackgroundResource(R.drawable.small_red_circle);
                }

                break;


            default:
                break;
        }


    }


    @Override
    public void onDelete() {


        TextView view = (TextView) dialog.getCurrentLongClickedView();

        if (!TextUtils.isEmpty(((EvaluateDetailResult2.DetectionBean.ApshellBean) view.getTag()).getImage())
                && ((EvaluateDetailResult2.DetectionBean.ApshellBean) view.getTag()).getImage().startsWith("http")) {
            needToDeleteOSSImgList.add(((EvaluateDetailResult2.DetectionBean.ApshellBean) view.getTag()).getImage());
        }

        if (null != view && rlContainer.indexOfChild(view) != -1) {
            rlContainer.removeView(view);
            tvList.remove(view);
            Log.e(TAG, "onDelete: deleteSuccessful");
        }

    }

    @Override
    public void selectImgFromGallery() {
        pickPhoto();
    }

    /**
     * 进入图片选择页面
     */
    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .start(getActivity(), AppearanceCheckFragment.this);
    }


    /**
     * 删除OSS服务器图片
     *
     * @param imgPath
     */
    private void deleteImg(String imgPath) {

        // 创建删除请求
        DeleteObjectRequest delete = new DeleteObjectRequest(HttpConstants.ALIYUN_OSS_BUCKET, imgPath);
        // 异步删除
        OSSAsyncTask deleteTask = MyApplication.getInstance().getOss().asyncDeleteObject(delete, new OSSCompletedCallback<DeleteObjectRequest, DeleteObjectResult>() {
                    @Override
                    public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
                        Log.e(TAG, "onSuccess: 删除成功 ");
                    }

                    @Override
                    public void onFailure(DeleteObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常
                            Log.e("ErrorCode", serviceException.getErrorCode());
                            Log.e("RequestId", serviceException.getRequestId());
                            Log.e("HostId", serviceException.getHostId());
                            Log.e("RawMessage", serviceException.getRawMessage());
                        }

                        dismissDialog();
                        SToast.show("删除失败，请重试！");
                    }
                }
        );
    }


    @Override
    public void onUploadOk(String imgUrl, Object tag) {

        --uploadImgCounter;
        if (!TextUtils.isEmpty(imgUrl))
            ((EvaluateDetailResult2.DetectionBean.ApshellBean) ((TextView) tag).getTag()).setImage(imgUrl);

        Log.e(TAG, "onUploadOk: " + imgUrl);

        if (uploadImgCounter == 0) {

            saveData();
        }
    }

    @Override
    public void onUploadFailed() {


    }
}
